<template>
    <el-form style="width: 40%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="图书编号">
            <el-input v-model="ruleForm.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="图书名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
            <el-input v-model="ruleForm.author"></el-input>
        </el-form-item>

        <el-form-item>
            <!-- submitForm 中的参数是 form 表单中的 ref -->
            <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    export default {
        name: 'BookUpdate',
        data() {
            return {
                ruleForm: {
                    id: '',
                    name: '',
                    author: ''
                },
                rules: {
                    name: [
                        { required: true, message: '图书名不能为空', trigger: 'blur' }
                    ],
                    author: [
                        { required: true, message: '作者不能为空', trigger: 'blur' }
                    ]
                }
            };
        },
        methods: {
            submitForm(formName) {
                // 保存一下当前 vue 对象
                const _this = this;
                // 先记住这样写，就是当所有校验通过的时候，valid为 true
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.put('http://localhost:8181/book/updateBook', this.ruleForm).then(function (response) {
                            if (response.data === 'success') {
                                _this.$alert('《'+_this.ruleForm.name+'》修改成功', '消息', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        _this.$router.push('/bookManage');
                                    }
                                });
                            }
                        })
                    } else {
                        // 校验没有通过
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        },
        created() {
            // 进入这个页面前的初始化
            // 拿到传过来的参数 id，拿参数的时候用 route，跳转用 router
            var id = this.$route.query.id;
            const _this = this;
            // 请求服务器
            axios.get('http://localhost:8181/book/findById/'+id).then(function (response) {
                _this.ruleForm = response.data;
            });
        }
    }
</script>

<style scoped>

</style>